package sample.utils;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.stream.Collectors;

public class PhoneUtils {
    private static final String replaceStr = "****";
    // 座机正则表达式
    private static final String phoneRegex = "0\\d{2,3}-\\d{7,8}|\\(?0\\d{2,3}[)-]?\\d{7,8}|\\(?0\\d{2,3}[)-]*\\d{7,8}";


    public static void main(String[] args) {
        System.out.println(hide("(010)56107280,15116911122"));
    }

    public static String hide(String phone){
        if(StringUtils.isEmpty(phone)) return phone;

        List<String> newPhones = Lists.newArrayList();
        if(phone.length()==11) {
            newPhones.add(hideMobile(phone));
        } else if(phone.contains(";") || phone.contains(",")) {
            String[] phones = phone.split(";|,");
            for (String p : phones) {
                if(p.matches(phoneRegex)) {
                    newPhones.add(hidePhone(p));
                } else if(p.length() == 11) {
                    newPhones.add(hideMobile(p));
                }
            }
        } else {
            newPhones.add(hidePhone(phone));
        }

        return newPhones.stream().collect(Collectors.joining(";"));

    }

    private static String hidePhone(String phone){
        String phoneNumber = phone.length() > 4 ? phone.substring(0, phone.length()-4) + replaceStr : phone;
        return phoneNumber;
    }

    private static String hideMobile(String mobilePhone){
        String phoneNumber = mobilePhone.substring(0, 3) + replaceStr + mobilePhone.substring(7, mobilePhone.length());
        return phoneNumber;
    }
}
